﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Net;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using VW.Golfgift;
using System.Net.Mail;
using OgilvyOne.BLL;

public partial class gift_index : BasePage
{
    protected string dealerpstr = "";
    protected string dealercstr = "var dcitys = Array();\n";
    protected string dealerstr = "var dealers = Array();\n";
    protected string modelstr = "var models=new Array();\n";
    protected string years = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        //if (!IsPostBack)
        {
            Response.AddHeader("p3p", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");

            camname.Value = "GOLF_201201";
            sourec.Value = FilterXss(Request.Params["utm_source"]);
            channel.Value = FilterXss(Request.Params["utm_medium"]) + (string.IsNullOrEmpty(Request.Params["utm_term"]) ? "" : "-") + FilterXss(Request.Params["utm_term"]);
        }
    }

    protected void Sub_click(object sender, EventArgs e)
    {
        string content = "";

        content += "username=" + username.Text;
        content += "&sex=" + sex.Text;

        content += "&mobile=" + mobile.Text;

        content += "&email=" + email.Text;


        content += "&id=" + int.Parse(this.model.Text);
        //model.Vico_model = this.model.Text == "26" ? "Golf旅行轿车" : "CrossGolf";
        content += "&dealerprovince=" + (string.IsNullOrEmpty(Request.Params["dealerprovince"]) ? 0 : int.Parse(Request.Params["dealerprovince"]));
        content += "&dealercity=" + (string.IsNullOrEmpty(Request.Params["dealercity"]) ? 0 : int.Parse(Request.Params["dealercity"]));
        content += "&dealer=" + (string.IsNullOrEmpty(Request.Params["dealer"]) ? 0 : int.Parse(Request.Params["dealer"]));

        content += "&buytime=" + Request.Params["year"] + Request.Params["month"];
        content += "&buybudget=" + buybudget1.Text + "-" + buybudget2.Text + "万";


        if (isagree.Checked)
        {
            content += "&isagree=1";
        }
        else
        {
            content += "&isagree=0";
        }
        content += "&isincept=" + isincept.Text;

        content += "&source=" + sourec.Value;
        content += "&camname=" + camname.Value;
        content += "&channel=" + channel.Value;
        content += "&ip=" + Request.UserHostAddress;
        if (Request.Cookies["__utmz"] != null && Request.Cookies["__utmz"].Value != null)
        {
            content += "&otherchannel=" + Request.Cookies["__utmz"].Value;
        }

        string res = TestdiverHttpPost(content, "http://vico1.vw.com.cn/newcms/testdrive/api/regsave.aspx");

        if (res.IndexOf("0") > -1)
        {
            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), Guid.NewGuid().ToString(), "alert('注册失败！请重试！');", true);
            //数据库保存失败
        }
        else
        {
            /*发送邮件到CallCenter
             * 代码编写人：陈鹏
             * 代码编写时间：2012.01.18 20:14
             */
            //发送邮件代码开始

            //1获取发送邮件内容
            string emailBody = "";
            emailBody += "您感兴趣的大众进口汽车车型：" + model.SelectedItem.Text + "<br/>\n";
            emailBody += "姓名：" + username.Text + "<br/>\n";
            emailBody += "称谓：" + sex.Text + "<br/>\n";
            emailBody += "手机号码：" + mobile.Text + "<br/>\n";
            emailBody += "电子邮件：" + email.Text + "<br/>\n";
            emailBody += "购车时间：" + Request.Params["year"] + Request.Params["month"] + "<br/>\n";
            emailBody += "购车预算：" + buybudget1.Text + "-" + buybudget2.Text + "万" + "<br/>\n";
 
            emailBody += "是否接受大众提供其他的市场活动信息：" + isincept.SelectedItem.Text + "<br/>\n";
            string flag = "";
            if (isagree.Checked)
            {
                flag = "是";
            }
            else
            {
                flag = "否";
            }
            emailBody += "是否接受数据保护条款：" + flag + "<br/>\n";

            DateTime now = DateTime.Now;
            emailBody += "提交时间：" + now.ToShortDateString() + " " + now.ToShortTimeString() + ":" + now.Second;

            bool resMail = false;
            try
            {
                resMail = sendMail("importgolf@vw.com.cn", emailBody);
                if (resMail)
                {
                    Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), Guid.NewGuid().ToString(), "alert('您的信息已经成功提交，我们会尽快跟您联系，谢谢。');window.location=\"index.aspx#/home\"", true);
                    //数据库保存成功并且邮件发送成功
                }
                else
                {
                    Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), Guid.NewGuid().ToString(), "alert('您的信息已经成功提交，我们会尽快跟您联系，谢谢。');window.location=\"index.aspx#/home\"", true);
                    //数据库保存成功 但是发送邮件失败
                }
            }
            catch (Exception ex)
            {
                //Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), Guid.NewGuid().ToString(), "alert('发送邮件遇到异常。错误信息：" + ex.Message + "');window.location=\"index.aspx#/home\"", true);
                //抛出异常信息
            }
        }

    }

    public static bool sendMail(string toMail, string emailBody)          //发送邮件
    {
        try
        {
            MailMessage dim = new MailMessage();
            dim.From = new MailAddress(toMail, "大众进口汽车高尔夫");     //发件人名称
            //dim.To.Add("golf@micromarketing.com.cn");                   //接受邮件地址-----(正式服)
            dim.To.Add("83891039@qq.com");                                //接受邮件地址-----(测试行)
            dim.Subject = "大众进口汽车高尔夫3.0预约试驾 - 注册数据";        //邮件主题
            dim.Body = emailBody;
            dim.IsBodyHtml = true;
            dim.BodyEncoding = System.Text.Encoding.UTF8;
            dim.Priority = System.Net.Mail.MailPriority.Normal;
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Credentials = new System.Net.NetworkCredential(dim.From.Address, "importgolfmail"); //发送邮件的密码
            smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            smtpClient.Host = "mail.vw.com.cn";  //发送邮件服务器
            smtpClient.Send(dim);
            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    //发送邮件代码结束


    public string TestdiverHttpPost(string content, string url)
    {
        System.Net.ServicePointManager.Expect100Continue = false;
        byte[] postData = Encoding.UTF8.GetBytes(content);
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        string str = "";
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postData.Length;
        try
        {
            using (System.IO.Stream outputStream = request.GetRequestStream())
            {
                outputStream.Write(postData, 0, postData.Length);
            }

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            if (response != null)
            {
                System.IO.Stream responseStream = response.GetResponseStream();
                StreamReader sr = new System.IO.StreamReader(responseStream);
                str = sr.ReadToEnd();
                responseStream.Close();
                sr.Close();
                response.Close();

            }
        }
        catch (Exception er)
        {
            str = "0";
        }
        return str;
    }

    private Hashtable ut = new Hashtable();

    protected string GetFirendAwards()
    {
        StringBuilder sb = new StringBuilder();
        IList datalist = LotteryDraw.GetLotteryDraw().GetFirendAwardList();
        ut[USER_TYPE_SINA] = "微博";
        ut[USER_TYPE_RENREN] = "人人网";
        ut[USER_TYPE_MSN] = "MSN";
        ut[USER_TYPE_EMAIL] = "邮箱注册";

        for (int i = 0; i < datalist.Count; i++)
        {
            string model = "CrossGolf";
            Hashtable t = (Hashtable)datalist[i];
            int gid = (int)t["FIREND_AWARD_GIFT_ID"];
            string img = GetGiftImg(gid);
            if (gid < 31)
            {
                model = "Golf旅行轿车";
            }
            else
            {
                gid -= 30;
            }

            sb.Append("<td><img src=\"" + img + "\" /></td>\n");
            sb.Append("<th>恭喜" + ut[t["USER_TYPE"].ToString()] + "用户：<a " + GetUserHelf((string)t["USER_TYPE"], (string)t["FIREND_SNS_ID"]) + ">" + t["FIREND_NAME"] + "</a><br />获得大众进口汽车" + model + "送出的<br /><a href=\"#\">#" + (gid < 10 ? "0" : "") + gid + "完美一天计划！</a><br />获奖日期：" + ((DateTime)t["ADDTIME"]).ToString("yyyy-MM-dd") + "<br/><img src=\"images/270.gif\" /></th>\n");
            if (i != datalist.Count - 1)
            {
                sb.Append("<td><img src=\"images/270.gif\" width=\"48\" /></td>\n");
            }
        }
        return sb.ToString();
    }

    private string GetGiftImg(int gid)
    {
        if (gid > 30) return "Cross_115x115/" + (gid - 30) + ".png";
        return "Variant_115x115/" + gid + ".jpg";
    }

    protected string GetUserAwards()
    {
        StringBuilder sb = new StringBuilder();
        IList ds = null;
        if (DateTime.Now.CompareTo(DateTime.Parse("2012-01-17")) >= 0)
        {
            ds = LotteryDraw.GetLotteryDraw().GetUserAwardGroup();
        }
        else
        {
            ds = new ArrayList();
            ds.Add("2012-01-10");
            ds.Add("2012-01-11");
            ds.Add("2012-01-12");
            ds.Add("2012-01-13");
            ds.Add("2012-01-14");
            ds.Add("2012-01-15");
            ds.Add("2012-01-16");
        }
        for (int i = 0; i < ds.Count; i++)
        {
            string date = (string)ds[i];
            sb.Append("<td valign=\"top\"><table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n");
            sb.Append("<tr>\n");
            sb.Append("<th>" + DateTime.Parse(date).ToString("M月dd日") + "获奖者<br /><img src=\"images/270.gif\" width=\"100\" /></th>\n");
            sb.Append("</tr>\n");
            IList datalist = LotteryDraw.GetLotteryDraw().GetUserAwardList(date);
            for (int u = 0; u < datalist.Count; u++)
            {
                Hashtable ut = (Hashtable)datalist[u];
                sb.Append("<tr>\n");
                sb.Append(" <td><a " + GetUserHelf((string)ut["USER_TYPE"], (string)ut["SNS_ID"]) + ">" + ut["USER_NAME"] + "</a></td>\n");
                sb.Append(" </tr>\n");
            }
            sb.Append("</table></td>\n");
            if (i != ds.Count - 1)
            {
                sb.Append("<td><img src=\"images/270.gif\" width=\"17\" /></td>\n");
            }
        }
        return sb.ToString();
    }

    private string GetUserHelf(string userType, string snsid)
    {
        if (userType == USER_TYPE_SINA)
        {
            return "href=\"http://weibo.com/" + snsid + "\" target=\"_blank\"";
        }
        else if (userType == USER_TYPE_RENREN)
        {
            return "href=\"http://www.renren.com/profile.do?id=" + snsid + "\" target=\"_blank\"";
        }
        return "href=\"javascript:void(0);\"";
    }
}
